
<template>
	<view class="upload">
		<view class="img_list">
			<view class="upload_img_wrap margin-right-sm" v-if="imgs.length == 0 && readOnly">
				<image src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-noImage.png"></image>
			</view>
			<view class="upload_img_wrap margin-right-sm" v-if="type == 'grid'" v-for="(item, index) in imgs" @click="previewImage(index)"
				:key="index">
				<image v-if="!readOnly" class="close_btn" @click.stop="clear(index)"
					src="https://qiniu.yooticloud.cn/shuzhigongdi/supervise/close.png" mode="scaleToFill" />
				<image v-if="imagesTypes.find(fileType => item.endsWith(fileType))" class="upload_img" :src="item"
					mode="scaleToFill" />
				<view class="text-center" v-else-if="filesTypes.find(fileType => item.endsWith(fileType))">
					<image v-if="item.endsWith('zip')" src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-zip.png"
						mode="heightFix" />
					<image v-else-if="item.endsWith('pdf')" src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-pdf.png"
						mode="heightFix" />
					<image v-else-if="item.endsWith('docx') || item.endsWith('doc')"
						src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-docx.png" mode="heightFix" />
					<image v-else-if="item.endsWith('xlsx') || item.endsWith('xls')" src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-xlsx.png"
						mode="heightFix" />
				</view>
				<view v-else class="text-xxl bg-grey light flex align-center full-size justify-center">
					<view class="text-center">
						<text class="cuIcon-text"></text>
						<view class="text-xs">other</view>
					</view>
				</view>
			</view>
			<view v-if="useSlot" @click.stop="chooseType">
				<slot name='uploadBtn'></slot>
			</view>
			<view class="upload_btn" v-else-if="imgs.length < num && !readOnly " @click="chooseType"></view>
			<uni-popup ref="popup" type="bottom" :animation="false">
				<view class="upload-popup bg-white padding-bottom-lg padding-lr padding-top">
					<view class="padding-bottom-lg">
						<view class="text-bold text-center">选择上传文件类型</view>
						<view class="padding-tb flex align-end">
							<view class="flex-1 text-center" @click="chooseImage">
								<image class="choose-file-type1" src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-image.png"
									mode="widthFix"></image>
								<view class="padding-top-sm">图片文件</view>
							</view>
							<view class="flex-1 text-center" @click="chooseMessageFile">
								<image class="choose-file-type2" src="https://qiniu.yooticloud.cn/shuzhigongdi/v1.1.0/icon-files.png"
									mode="widthFix"></image>
								<view class="padding-top-sm">其他文件</view>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<LwCompress ref="lwCompress"></LwCompress>
	</view>
</template>

<script>
import LwCompress from './h-compress'
import {
	BaseUrl
} from '@/utils/env'

export default {
	props: {
		url: {
			type: String,
			default: BaseUrl + '/file/upload'
		},
		type: {
			type: String,
			default: 'grid' // grid list grid-list
		},
		name: {
			type: String,
			default: 'file'
		},
		value: {
			type: String,
			default: ''
		},
		fileSize:{
			type: String,
			default: '10',
		},
		readOnly: {
			type: Boolean,
			default: false
		},
		useSlot: {
			type: Boolean,
			default: false
		},
		imagesTypes: {
			type: Array,
			default: () => ['.jpg', '.jpeg', '.png']
		},
		filesTypes: {
			type: Array,
			default: () => ['.docx', '.xlsx', '.xls', '.doc', '.pdf', '.zip']
		},
		fileType: {	//上传类型为图片、文件、图片 + 文件
			type: String,	// image, file,
			default: '',
		},
		max: {
			type: Number,
			default: 1
		}
	},
	components: {
		LwCompress
	},
	watch: {
		value: {
			handler() {
				this.list = []
				this.imgs = []
				const str = this.value;
				let imgList = [];
				switch (this.type) {
					case 'list':
						// this.list = this.value;
						imgList = str.split(',')
						break
					case 'grid-list':
						this.value.forEach(item => {
							if (this.imagesTypes.includes(item.fileType)) {
								imgList = [...this.imgs, item.fileUrl]
							} else {
								this.list = [...this.list, item]
							}
						})
						break
					default:
						if (str) {
							imgList = str.split(',')
						}
						break
				}
				this.imgs = imgList.filter(item => !!item);
			},
			immediate: true
		},
		max: {
			handler(newVal) {
				if (newVal && typeof newVal === 'number') {
					this.num = newVal
				}
			},
			immediate: true
		}
	},
	data() {
		return {
			imgs: [],
			num: 1
		}
	},
	methods: {
		clear(index) {
			this.imgs.splice(index, 1)
			const v = this.imgs.join(',')
			this.$emit('input', v)
		},
		chooseType() {
			// #ifndef H5
			if( this.fileType == 'image'){
				this.chooseImage();
			}else if(this.fileType == 'file'){
				this.chooseMessageFile();
			} else{
				// #ifdef MP-WEIXIN
				this.$refs.popup.open()
				// #endif
				// #ifdef APP-PLUS
				this.$refs.popup.open();
				// #endif
				// #ifndef MP-WEIXIN
				// this.chooseImage()
				// #endif
			}
			// #endif
			
			// #ifdef H5
			this.chooseMessageFile();
			// #endif
		},

		//回显图片 判断是新增修改  注意：小程序内部操作base64会导致卡死，需要展示的时候显示微信url，提交用Base64提交
		setImg(item) {
			return setImg(item)
		},
		previewImage(index) {
			const urls = this.imgs.filter(
				item =>
					!!this.imagesTypes.find(types => {
						const str = item.toLowerCase()
						return str.endsWith(types)
					})
			)
			const fileTypes = ['.doc', '.docx', '.json', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf']
			const file = this.imgs[index].toLowerCase()
			const current = urls.findIndex(item => item == this.imgs[index])
			if (current > -1) {
				uni.previewImage({
					urls,
					current
				})
			} else {
				wx.downloadFile({
					// 示例 url，并非真实存在
					url: this.imgs[index],
					success: function (res) {
						const filePath = res.tempFilePath
						wx.openDocument({
							filePath: filePath,
							success: function (res) {
								console.log('打开文档成功')
							},
							fail() {
								uni.showToast({
									icon: 'none',
									title: '格式不支持预览'
								})
							}
						})
					}
				})
			}

			// if (fileTypes.find(item => file.endsWith(item)))
			//  else {
			// 	uni.showToast({
			// 		icon: 'error',
			// 		title: '格式不支持预览'
			// 	})
			// }
		},
		urlTobase64(url) {
			//只在小程序有用
			uni.getFileSystemManager().readFile({
				filePath: url,
				//选择图片返回的相对路径
				encoding: 'utf-8',
				//编码格式
				success: res => {
					console.log(res)
					//成功的回调
				},
				fail: res => {
					console.log('错误')
					uni.hideLoading()
				}
			})
		},
		chooseImage() {
			this.$refs.popup.close()
			uni.chooseImage({
				count: this.num,
				success: res => {
					this.uploadImages(res.tempFilePaths)
				}
			})
		},
		chooseFile() {
			this.$refs.popup.close()
			uni.chooseFile({
				count: this.num,
				success: res => {
					this.uploadImages(res.tempFilePaths), true
				}
			})
		},
		chooseMessageFile() {
			this.$refs.popup.close()
			// #ifdef MP-WEIXIN
			uni.chooseMessageFile({
				count: this.num,
				type: 'file',
				extension: this.filesTypes,
				success: res => {
					this.uploadImages(
						res.tempFiles.map(item => item.path),
						true
					)
				}
			})
			// #endif
			// #ifdef H5
			uni.chooseFile({
				count: this.num,
				success: res => {
					this.uploadImages(
						res.tempFiles.map(item => item.path),
						true
					)
				}
			
			})
			// #endif
			// #ifdef APP-ANDROID
			this.selectAndroidAPPFile()
			// #endif
		},
		uploadFile(filePath) {
			const {
				url,
				name
			} = this
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url, //仅为示例，非真实的接口地址
					filePath,
					name,
					timeout: 15000,
					success: ({
						data
					}) => {
						resolve(data)
					},
					fail: err => {
						resolve(err)
					}
				})
			})
		},
		async uploadImages(miniImgs = [], flag) {
			try {
				let imgs = []
				if (flag) {
					imgs = miniImgs
					uni.showLoading({
						mask: true,
						title: '文件上传中...'
					})
				} else {
					// 压缩图片
					uni.showLoading({
						mask: true,
						title: '图片处理中...'
					})
					for (let i = 0; i < miniImgs.length; i++) {
						const baseImg = await this.$refs.lwCompress.compress({
							src: miniImgs[i],
							maxSize: 1000,
							fileType: 'jpg',
							quality: 0.5,
							minSize: 800 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
						})
						imgs.push(baseImg)
					}
					// 压缩成功
					uni.showLoading({
						mask: true,
						title: '图片上传中...'
					})
				}
				const onlinePromise = imgs.map(item => {
					return this.uploadFile(item)
				})
				const onlineImgs = await Promise.all(onlinePromise)
				uni.hideLoading()
				let count = 0
				const images = onlineImgs.map(item => {
					const data = JSON.parse(item)
					if (data.code == 0) {
						count++
						return data.data
					}
					return ''
				})
				uni.showToast({
					icon: 'success',
					title: count + '个文件上传成功'
				})
				this.imgs = [...this.imgs, ...images.filter(item => !!item)].slice(0, this.num);
				const value = this.imgs.join(',')
				this.$emit('input', value)
			} catch (e) {
				if (e instanceof Array && e.length) {
					let count = 0
					const images = e.map(item => {
						const data = JSON.parse(item)
						if (data.code == 0) {
							count++
							return data.data
						}
						return ''
					})
					uni.showToast({
						icon: 'success',
						title: count + '个文件上传成功'
					})
				} else {
					uni.showToast({
						icon: 'success',
						title: '文件上传失败'
					})
				}
			}
		},
		// #ifdef APP-ANDROID
		selectAndroidAPPFile() {
			var AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
			console.log('Android'); //android
			AfDocument.openMode({
				size: this.num, //选择总数量
				// paths: ['/storage/emulated/0', '/storage/emulated/0/A', ], //自定义选择目录
				isDown: true, //是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件） 
				types: [{
					name: '文档',
					value: this.filesTypes.map(item => item.replace('.',''))
				}]
			}, (result) => {
				console.log("" + JSON.stringify(result));

				if (result.res.length > 0) {
					// let size = this.fileSize * 1024;
					let fileList = result.res;
					
					// if (result.res[0].sizeHolp > this.FZ_KB) {
					// 	uni.showToast({
					// 		icon: 'none',
					// 		mask: true,
					// 		title: '文件大小不能超过10M',
					// 	});
					// } else {
					// 	this.selectPath = result.res[0].path;
					// 	this.selectName = result.res[0].name;
					// 	console.log("-----tempFiles----" + JSON.stringify(result.res[0])); //临时文件地址  
					// }
					
					this.uploadImages(fileList.map(f => f.path), true);

				} else {
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '选择失败请重试',
					});
				}

			})

		},
		// #endif
	}
}
</script>

<style lang="less"
	scoped>
	.upload_img {
		width: 130rpx;
		height: 130rpx;
	}

	.choose-file-type1 {
		width: 200rpx;
		height: 200rpx;
	}

	.choose-file-type2 {
		width: 160rpx;
		height: 160rpx;
	}

	.upload_btn {
		width: 130rpx;
		height: 130rpx;
		background: url(https://qiniu.yooticloud.cn/shuzhigongdi/supervise/opinion_add.png) no-repeat;
		background-size: 100% 100%;
	}

	.upload-popup {
		border-radius: 10rpx 10rpx 0 0;
		z-index: 9999;
	}

	.upload_img_wrap {
		width: 130rpx;
		height: 130rpx;
		display: block;
		position: relative;

		image {
			max-height: 130rpx;
		}
	}

	.close_btn {
		width: 42rpx;
		height: 42rpx;
		position: absolute;
		z-index: 10;
		right: -20rpx;
		top: -20rpx;
	}

	.img_list {
		display: flex;
		flex-wrap: wrap;

		>view {
			width: 130rpx;
			margin-left: 3%;
			margin-top: 20rpx;

			&:first-child {
				// margin-left: 0;
			}
		}
	}
</style>